<?php

namespace app\api\controller;

use app\admin\model\OilOrder;
use app\admin\model\Order;
use app\admin\model\RechargeOrder;
use app\common\controller\Frontend;
use EasyWeChat\Kernel\Exceptions\Exception;

class Alipay extends Frontend
{
    protected $noNeedLogin = ['paySuccess', 'oilOrderPaySuccess', 'rechargeSuccess'];

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * @param OilOrder $order
     * @return string
     */
    public function paySuccess(OilOrder $order)
    {
        $message = $this->request->post();
        if ($message['trade_status'] == 'TRADE_SUCCESS') {
            $message['transaction_id'] = $message['trade_no'];
            exit($order->paySuccess($message) ? 'success' : 'fail');
        }
        return 'fail';
    }

    /**
     * @param OilOrder $order
     * @param WechatModel $wechat
     * @return void
     * @throws Exception
     */
    public function oilOrderPaySuccess(OilOrder $order, WechatModel $wechat)
    {
        $app = $wechat->getPayment();
        $response = $app->handlePaidNotify(function ($message, $fail) use ($order) {
            if ($message['result_code'] == 'SUCCESS' && $message['return_code'] == 'SUCCESS') {
                return $order->paySuccess($message);
            }
            return false;
        });

        $response->send();
    }

    /**
     * @param RechargeOrder $order
     * @param WechatModel $wechat
     * @return void
     * @throws Exception
     */
    public function rechargeSuccess(RechargeOrder $order, WechatModel $wechat)
    {
        $app = $wechat->getPayment();
        $response = $app->handlePaidNotify(function ($message, $fail) use ($order) {
            if ($message['result_code'] == 'SUCCESS' && $message['return_code'] == 'SUCCESS') {
                return $order->paySuccess($message);
            }
            return false;
        });

        $response->send();
    }

}